#include <QCoreApplication>
#include <QDateTime>
#include <QDebug>
#include <QtXml>
#include <QFile>
#include <qbuffer.h>
#include <qglobal.h>
#include <qxmlstream.h>

void processUiFile(const QString &filePath) {
    QFile file(filePath);
    if (!file.open(QIODevice::ReadOnly | QIODevice::Text)) {
        qCritical() << "Error: Cannot open file";
        return;
    }

    QBuffer output;
    output.open(QIODevice::WriteOnly | QIODevice::Text);
    QXmlStreamReader reader(&file);
    QXmlStreamWriter writer(&output);

    writer.setAutoFormatting(true);

    bool skiped = false;
    while (!reader.atEnd()) {
        auto token = reader.readNext();

        switch (token) {
        case QXmlStreamReader::StartDocument: {
            writer.writeStartDocument();
            break;
        }
        case QXmlStreamReader::StartElement: {
            if (reader.name().toString() == "colorrole" && reader.attributes().value("role") == "PlaceholderText") {
                skiped = true;
                reader.skipCurrentElement();
                /// Fix: 该节点跳过时，前面已经追加过 '\n    ' 内容, 所以这里向前移除一个空白部分
                output.seek(output.pos()-1);
                qDebug() << "发现:" + reader.text().toString();
                continue;
            }

            writer.writeStartElement(reader.name().toString());
            foreach (const auto &attr, reader.attributes()) {
                writer.writeAttribute(attr.name().toString(), attr.value().toString());
            }
            break;
        }
        case QXmlStreamReader::EndElement: {
            writer.writeEndElement();
            break;
        }
        case QXmlStreamReader::Characters: {
            if (!skiped) {
                writer.writeCharacters(reader.text().toString());
            }
            skiped = false;
            break;
        }
        default:
            writer.writeCurrentToken(reader);
        }
    }

    file.close();
    if (file.open(QIODevice::WriteOnly | QIODevice::Text)) {
        file.write(output.data());
        file.close();
    }

    qInfo() << "processed!";
}

int main(int argc, char *argv[])
{
    QCoreApplication a(argc, argv);
    if (argc < 2) {
        qCritical() << "Usage:" << argv[0] << "<filename.ui>";
        return 1;
    }

    const QString filePath = argv[1];

    // 硬核校验文件扩展名
    QFileInfo fi(filePath);
    if (fi.suffix().toLower() != "ui") {
        qCritical() << "Fatal: Only .ui files are supported";
        return 2;
    }

    if (!fi.exists()) {
        qCritical() << "File not exist:" << filePath;
        return 3;
    }

    processUiFile(filePath);
    return 0;
}
